package com.tckj.boot.modules.web.admin;

import com.tckj.boot.common.utils.QueryHelp;
import com.tckj.boot.common.utils.ResponseUtil;
import com.tckj.boot.infrastructure.storage.StorageService;
import com.tckj.boot.modules.domain.sys.storage.application.FileStorageService;
import com.tckj.boot.modules.domain.sys.storage.application.dto.StorageQueryDto;
import com.tckj.boot.modules.domain.sys.storage.model.FileStorage;
import com.tckj.boot.modules.domain.sys.storage.model.FileStorageRepository;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.validation.constraints.NotNull;
import java.io.IOException;

@RestController
@RequestMapping("/admin/storage")
@Validated
public class AdminStorageController {
    private final Log logger = LogFactory.getLog(AdminStorageController.class);

    @Autowired
    private StorageService storageService;
    @Autowired
    private FileStorageRepository repository;
    @Autowired
    private FileStorageService fileStorageService;

    @GetMapping("/list")
    public Object list(StorageQueryDto query, Pageable pageable) {
        Page<FileStorage> storageList = repository.findAll((root,criteriaQuery,criteriaBuilder)->QueryHelp.getPredicate(root,query,criteriaBuilder),pageable);
        return ResponseUtil.ok(storageList);
    }

    @PostMapping("/create")
    public Object create(@RequestParam("file") MultipartFile file) throws IOException {
        String originalFilename = file.getOriginalFilename();
        FileStorage fileStorage = storageService.store(file.getInputStream(), file.getSize(), file.getContentType(), originalFilename);
        return ResponseUtil.ok(fileStorage);
    }

    @PostMapping("/read")
    public Object read(@NotNull Long id) {
        FileStorage storageInfo = fileStorageService.findById(id);
        if (storageInfo == null) {
            return ResponseUtil.badArgumentValue();
        }
        return ResponseUtil.ok(storageInfo);
    }

    @PostMapping("/delete")
    public Object delete(@RequestBody FileStorage litemallStorage) {
        String key = litemallStorage.getKey();
        if (StringUtils.isEmpty(key)) {
            return ResponseUtil.badArgument();
        }
        fileStorageService.deleteByKey(key);
        storageService.delete(key);
        return ResponseUtil.ok();
    }
}
